#include<WinSock2.h>
#include<ws2tcpip.h>
#include<stdio.h>

#define PORT 10492

DWORD WINAPI Communication(LPVOID lpParameter)
{
	DWORD dwTid = GetCurrentThreadId();
	SOCKET socket = (SOCKET)lpParameter;
	LPSTR szRequest = (LPSTR)HeapAlloc(GetProcessHeap(), 0, 1024);
	int iResult;
	int bytesSent;
	iResult = recv(socket, szRequest, 1024, 0);
	if (iResult == 0)
	{
		printf("Connect Failed...\nPress any key to continue...\n");
		HeapFree(GetProcessHeap(), 0, szRequest);
		closesocket(socket);
		getchar();
		return 1;
	}
	else if (iResult == SOCKET_ERROR)
	{
		printf("Socket Error: %d...\nPress any key to continue...\n", WSAGetLastError());
		HeapFree(GetProcessHeap(), 0, szRequest);
		closesocket(socket);
		getchar();
		return 1;
	}
	else if (iResult > 0)
	{
		printf("Suceeded in connecting\n");
		printf("\tCurrent id(%d)\treceived Byte: %d\n", dwTid, iResult);
		printf("\tCurrent id(%d)\treceived String is: %s\n", dwTid, szRequest);

		if (lstrcmpi(szRequest, "download file") == 0)
		{
			HANDLE hFile;
			LPVOID lpReadBuffer;
			DWORD dwByteRead;
			DWORD dwFileSize;
			DWORD dwSentFile = 0;
			hFile = CreateFile("download.txt", GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
			if (hFile == INVALID_HANDLE_VALUE)
			{
				printf("Can't Create file handle... error: %d\n",GetLastError());
				send(socket, "error", 6, 0);
				closesocket(socket);
				return 1;

			}
			dwFileSize = GetFileSize(hFile, nullptr);
			while (1)
			{
				if (!ReadFile(hFile, lpReadBuffer, 4096, &dwByteRead, NULL))
				{
					printf("Can't read from file error:%d\n", WSAGetLastError());
					closesocket(socket);
					CloseHandle(hFile);
					return 1;
				}

				bytesSent = send(socket, (LPSTR)lpReadBuffer, dwByteRead, 0);
				if (bytesSent == SOCKET_ERROR);
				{
					printf("SentMessageFailed error:%d\n", WSAGetLastError());
					closesocket(socket);
					CloseHandle(hFile);
					return 1;
				}
				printf("Thread(%d)Sent  %d bytes\n", dwTid, bytesSent);
				dwSentFile += dwByteRead;
				if (dwSentFile == dwFileSize)
				{
					printf("thread(%d)sent down!", dwTid);
					break;
				}
			}
			HeapFree(GetProcessHeap(), 0, lpReadBuffer);
			CloseHandle(hFile);
			closesocket(socket);

		}
		HeapFree(GetProcessHeap, 0, szRequest);
		closesocket(socket);
		return 0;
	}
}

int __cdecl main()
{
	WSADATA wsaData;
	SOCKET ListenSocket = INVALID_SOCKET;
	SOCKET ClientSocket = INVALID_SOCKET;
	addrinfo *result = nullptr,hints;
	int iResult;

	iResult = WSAStartup(MAKEWORD(2, 2), &wsaData);
	if (iResult != 0)
	{
		printf("wsastartup failed\n");
		getchar();
		return 1;
	}
	ZeroMemory(&hints, sizeof(addrinfo));
	hints.ai_family = AF_INET;
	hints.ai_socktype = SOCK_STREAM;
	hints.ai_protocol = IPPROTO_TCP;
	hints.ai_flags = AI_PASSIVE;

}